/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.dafe.partyband.services.api;

import java.awt.event.ActionEvent;
import java.net.URI;
import java.util.Collection;
import javax.swing.AbstractAction;
import org.dafe.partyband.db.api.IAuthor;
import org.dafe.partyband.db.api.ISong;
import org.dafe.partyband.dochandler.DesktopActions;
import org.openide.util.Lookup;
import org.openide.util.Lookup.Result;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;

/**
 *
 * @author simda15
 */
public class Go2URIAction extends AbstractAction implements LookupListener {
    
    private final IURIActionDescription<ISong> songActionDesc;
    private Result<ISong> lkpResult;
    private final IURIActionDescription<IAuthor> authorActionDesc;

    public Go2URIAction(IURIActionDescription<ISong> songActionDesc, Lookup songsLkp) {
        super(songActionDesc.getName());
        this.songActionDesc = songActionDesc;
        this.authorActionDesc = null;
        init(songsLkp);
    }

    public Go2URIAction(Lookup songsLkp, IURIActionDescription<IAuthor> authorActionDesc) {
        super(authorActionDesc.getName());
        this.authorActionDesc = authorActionDesc;
        this.songActionDesc = null;
        init(songsLkp);
    }
    
    private void init(Lookup songsLkp) {
        this.lkpResult = songsLkp.lookupResult(ISong.class);
        lkpResult.addLookupListener(this);
        updateEnabled();
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        Collection<? extends ISong> items2Browse = lkpResult.allInstances();
        for (ISong song : items2Browse) {
            if (songActionDesc != null) {
                URI songURI = songActionDesc.getURI(song);
                if (songURI != null) {
                    DesktopActions.browse(songURI);
                }
            } else if (authorActionDesc != null) {
                URI authorURI = authorActionDesc.getURI(song.getAuthor());
                if (authorURI != null) {
                    DesktopActions.browse(authorURI);
                }
            }
        }
    }

    @Override
    public void resultChanged(LookupEvent le) {
        updateEnabled();
    }

    private void updateEnabled() {
        setEnabled(DesktopActions.isBrowseSupported() && lkpResult.allInstances().size() > 0);
    }
    
}
